﻿using StackExchange.Redis;

namespace Services
{
    public interface IRedisHelper
    {
        Task SetString(string key, string value);
        Task GetString(string key);
    }

    public class RedisHelper : IRedisHelper, IDisposable
    {
        private ConnectionMultiplexer _redisConnection;
        private readonly object _redisConnectionLock = new();

        public void Dispose()
        {
            if (_redisConnection.IsNotEmpty())
            {
                _redisConnection.Close();
            }

            GC.SuppressFinalize(this);
        }

        private ConnectionMultiplexer GetConnect()
        {
            if (_redisConnection.IsNotEmpty() && _redisConnection.IsConnected)
            {
                return _redisConnection;
            }

            lock (_redisConnectionLock)
            {
                if (_redisConnection.IsNotEmpty())
                {
                    _redisConnection.Dispose();
                }

                var redisOption = ConfigurationOptions.Parse(AppSetting.ConnectionStrings.Redis.Server);
                redisOption.Password = AppSetting.ConnectionStrings.Redis.Password;
                redisOption.DefaultDatabase = AppSetting.ConnectionStrings.Redis.DefaultDatabase;

                _redisConnection = ConnectionMultiplexer.Connect(redisOption);

                return _redisConnection;
            }
        }

        private IDatabase GetDatabase()
        {
            return GetConnect().GetDatabase();
        }

        public async Task SetString(string key, string value)
        {
            await GetDatabase().StringSetAsync(key, value);
        }

        public async Task GetString(string key)
        {
            await GetDatabase().StringGetAsync(key);
        }
    }
}
